// 管理用户数据相关

import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { login } from '@/apis/user/index.js'
import router from '@/router'

// import { useCartStore } from './cartStore'
// import { mergeCartAPI } from '@/apis/cart'


export const useUserStore = defineStore('user', () => {

  // const cartStore = useCartStore()
  // // 1. 定义管理用户数据的state

  const userInfo = ref({})

  // 2. 定义获取接口数据的action函数

  const getUserInfo = async (loginForm) => {

    try {
      const res = await login(loginForm)
      const data = res.data; // 假设返回的数据在 res 的 data 属性中
      handleLoginSuccess(data);
    } catch (error) {
      handleLoginError(error);
    }

  }
  const handleLoginSuccess = (data) => {
    userInfo.value = data
    // 处理登录成功的逻辑
    ElMessage({type: 'success', message: `欢迎你${ data.name }`})
    localStorage.setItem('userInfo', JSON.stringify(data));
    router.push('/');
  }
  const handleLoginError = (error) => {
    // 处理登录失败的逻辑

  }

  const updateUserinfo = (newUserinfo) => {
    userInfo.value = newUserinfo
  }

  // 退出时清除用户信息
  const clearUserInfo = () => {
    userInfo.value = {}

  }

  //解绑邮箱 直接将userinfo的email 置空
  const unbindemail = () => {
    userInfo.value.email = null
  }
  //绑定成功将邮箱存储
  const bindemail = (email) => {
    userInfo.value.email = email
  }

  // 3. 以对象的格式把state和action return
  return {
    userInfo,
    getUserInfo,
    clearUserInfo,
    updateUserinfo,
    unbindemail, bindemail

  }
}, {
  persist: true,
})